package org.ee.core;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;

/**
 *
 * @Author zlj
 * @Date 2025/11/9 00:01
 */
public class ProtocolDetectHandler extends ByteToMessageDecoder {
    private static final Logger logger = LogManager.getLogger(ProtocolDetectHandler.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        //数据不足等待
        if (in.readableBytes() < 4) return;
        in.markReaderIndex();
        ProtocolDefinition protocol = ProtocolRegistry.detect(in);
        in.resetReaderIndex();

        if (protocol != null) {
            logger.info("检测到协议:{}", protocol.getName());
            ChannelPipeline pipeline = ctx.pipeline();
            protocol.setupPipeline(pipeline);
            pipeline.remove(this);//移除检测器，后续交给handler处理

        } else {
            logger.debug("未知协议，关闭连接");
            ctx.close();
        }

    }
}
